package com.qqt.csr.web.service;

import com.qqt.csr.common.idempotent.Idempotent;
import com.qqt.csr.common.idempotent.RequestKeyParam;
import com.qqt.csr.common.session.SessionContextHolder;
import com.qqt.csr.im.entity.Account;
import com.qqt.csr.route.dto.resp.CsStatusDTO;
import com.qqt.csr.route.service.CsStatusService;
import com.qqt.csr.workbench.entity.SkillSet;
import com.qqt.csr.web.vo.resp.CsStatusRespVO;
import com.qqt.csr.workbench.service.SkillSetMemberService;
import com.qqt.csr.workbench.service.SkillSetService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class SwitchingCsStatusService {

    @Autowired
    private ClosingConversationService closingConversationService;
    @Autowired
    private ImAccountService imAccountService;
    @Autowired
    private SkillSetMemberService skillSetMemberService;
    @Autowired
    private CsStatusService csStatusService;
    @Autowired
    private SkillSetService skillSetService;

    /**
     * 切换客服状态
     *
     * @param csId
     * @param readyStatus
     * @param workStatus
     */
    @Idempotent(model = "skill-set:m:")
    public CsStatusRespVO switchStatus(@RequestKeyParam Long csId, Integer readyStatus, Integer workStatus) {
        String tenantId = SessionContextHolder.getHeaderInfo().getTenantId();

        List<Long> csSkillSetIdList = skillSetMemberService.getCsSkillSetIdList(csId);
        if (readyStatus.equals(1) && workStatus.equals(0)) {
            Map<Long, SkillSet> skillSetMap = skillSetService.getSkillSetMap(tenantId);
            csSkillSetIdList.removeIf(skillSetId -> skillSetMap.get(skillSetId) == null);
        }
        csStatusService.switchStatus(csId, tenantId, readyStatus, workStatus, csSkillSetIdList);

        if (readyStatus.equals(0)) {
            try {
                // 切换为未就绪，需要关闭所有会话
                log.info("客服关闭所有会话，csId:{}", csId);
                closingConversationService.closeAllConversation(csId);
                log.info("成功关闭客服所有会话，csId:{}", csId);
            } catch (Exception e) {
                log.error("关闭客服所有会话异常，csId:{}", csId, e);
            }
        }

        // 创建或者更新客服IM账号
        String csName = SessionContextHolder.getHeaderInfo().getNickName();
        String csHeadImg = SessionContextHolder.getHeaderInfo().getHeadImgUrl();
        Account account = imAccountService.createOrUpdateCsImAccount(csId, csName, csHeadImg);
        String webSocketUrl = imAccountService.getWebsocketAddress(tenantId, account, SessionContextHolder.getHeaderInfo().getDeviceFlag(), SessionContextHolder.getHeaderInfo().getDeviceType());

        return CsStatusRespVO.builder()
                .workStatus(workStatus)
                .readyFlag(readyStatus)
                .imUserFlag(account != null ? account.getAccountUserId() : StringUtils.EMPTY)
                .imAccountId(account != null ? account.getId() : 0L)
                .webSocketUrl(webSocketUrl)
                .build();
    }

    /**
     * 查询客服状态
     *
     * @param csId
     * @return
     */
    public CsStatusRespVO queryStatus(String tenantId, Long csId, String csName, String csHeadImg) {
        if (csId == null) {
            return CsStatusRespVO.builder().workStatus(0).readyFlag(0).build();
        }

        CsStatusDTO csStatus = csStatusService.queryStatus(csId);
        // 刷新IM账号信息
        Account account = imAccountService.createOrUpdateCsImAccount(csId, csName, csHeadImg);
        String webSocketUrl = imAccountService.getWebsocketAddress(tenantId, account, SessionContextHolder.getHeaderInfo().getDeviceFlag(), SessionContextHolder.getHeaderInfo().getDeviceType());

        return CsStatusRespVO.builder()
                .workStatus(csStatus.getWorkStatus())
                .readyFlag(csStatus.getReadyFlag())
                .imUserFlag(account != null ? account.getAccountUserId() : StringUtils.EMPTY)
                .imAccountId(account != null ? account.getId() : 0L)
                .webSocketUrl(webSocketUrl)
                .build();
    }
}
